package org.act.xservices.rt.xcontainer.message.builder;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import org.act.xservices.rt.xcontainer.framework.IContainerEnvironment;
import org.act.xservices.rt.xcontainer.framework.config.IConfigElement;
import org.act.xservices.rt.xcontainer.framework.config.IConfigurable;

public class MessageBuilderFactory implements IConfigurable{

	private Logger log = IContainerEnvironment.containerLogger;
	
	private Map<String, IMessageBuilder> buildersMap = new HashMap<String, IMessageBuilder>();
	
	
	public void config(IConfigElement buildersElement) throws Exception {

		for (IConfigElement builderConfig : buildersElement.getChildren()) {

			String contentType = builderConfig.getAttribute("contentType");
			String builderClass = builderConfig.getAttribute("class");

			try {
				if (builderClass != null && contentType != null) {
					IMessageBuilder builder = (IMessageBuilder) Class.forName(builderClass).newInstance();

					builder.setContentType(contentType);

					addMessageBuilder(builder);

					log.info("Succeed add MessageBuilder for: " + contentType);
				} else {
					log.info("Error MessageBuilder Parameter: " + contentType + " "
							+ builderClass);
				}
			} catch (Exception e) {
				log.info("Failed add MessageBuilder for: " + contentType);
				e.printStackTrace();
			}

		}

	}
	
	
	private void addMessageBuilder(IMessageBuilder builder) {
		
		buildersMap.put(builder.getContentType(), builder);
		
	}
	
	public IMessageBuilder getMessageBuilder(String contentType){
		return buildersMap.get(contentType);
	}
	
}
